import Vue from 'vue';
import Router from 'vue-router';
import { api_url, ERR_OK, buildType, isXxtb, isChannel, zxxfdb_id } from '@/config/config';
import { Base64 } from '@/utils/base64';
import store from '../store';

if (process.env.NODE_ENV === 'development') {
  Vue.use(Router);
}
// Vue.use(Router);


// 子页面用‘_’分隔，第一个为首页
const pages = {
  IndexPage: resolve => require.ensure([], () => resolve(require('@/pages/index_page/index_page')), 'index_page'),
  Auth: resolve => require.ensure([], () => resolve(require('@/pages/login/auth')), 'auth'),
  Mine: resolve => require.ensure([], () => resolve(require('@/pages/mine/mine')), 'mine'),
  // Login: resolve => require.ensure([], () => resolve(require('@/pages/login/login')), 'login'),
  // Invitation: resolve => require.ensure([], () => resolve(require('@/pages/invite/invitation')), 'invite'),
  CashOut: resolve => require.ensure([], () => resolve(require('@/pages/cashout/cashout')), 'cashout'),
  CashOutRecord: resolve => require.ensure([], () => resolve(require('@/pages/cashoutrecord/cashoutrecord')), 'cashoutrecord'),
  Scholarship: resolve => require.ensure([], () => resolve(require('@/pages/scholarship/scholarship')), 'scholarship'),
  MyOrder: resolve => require.ensure([], () => resolve(require('@/pages/myorder/myorder')), 'myorder'),
  ClassList: resolve => require.ensure([], () => resolve(require('@/pages/class/classlist')), 'class'),
  CourseList: resolve => require.ensure([], () => resolve(require('@/pages/class/courselist')), 'class'),
  TbCourseList: resolve => require.ensure([], () => resolve(require('@/pages/class/tbcourselist')), 'class'),
  PlayVideo: resolve => require.ensure([], () => resolve(require('@/pages/play/playvideo')), 'play'),
  PlayAudio: resolve => require.ensure([], () => resolve(require('@/pages/play/playaudio')), 'play'),
  PlayRecord: resolve => require.ensure([], () => resolve(require('@/pages/play/playrecord')), 'play'),
  PayVip: resolve => require.ensure([], () => resolve(require('@/pages/pay/payvip')), 'pay'),
  PayCount: resolve => require.ensure([], () => resolve(require('@/pages/pay/paycount')), 'pay'),
  MyCollect: resolve => require.ensure([], () => resolve(require('@/pages/mycollect/mycollect')), 'mycollect'),
  ClassDetail: resolve => require.ensure([], () => resolve(require('@/pages/classdetail/classdetail')), 'classdetail'),
  AudioDetail: resolve => require.ensure([], () => resolve(require('@/pages/classdetail/audiodetail')), 'audiodetail'),
  PayVipList: resolve => require.ensure([], () => resolve(require('@/pages/pay/payviplist')), 'pay'),
  PaySuccess: resolve => require.ensure([], () => resolve(require('@/pages/pay/success')), 'pay'),
  Dictionary: resolve => require.ensure([], () => resolve(require('@/pages/dictionary/dictionary')), 'dictionary'),
  ExChange: resolve => require.ensure([], () => resolve(require('@/pages/exchange/exchange')), 'exchange'),
  DicResults: resolve => require.ensure([], () => resolve(require('@/pages/dictionary/results')), 'dictionary'),
  NotChannel: resolve => require.ensure([], () => resolve(require('@/pages/notchannel/index')), 'error'),
  Bind: resolve => require.ensure([], () => resolve(require('@/pages/bind/bind')), 'bind')
};

// 后台子路由
// pages.Invite.children = {
// Down // /invite/down
// };

// 配置路由
const setRoutes = function(routeItems, path = '', defaultRoute, callback) {
  if (!routeItems) return [];
  let res = [],
    first = true;
  defaultRoute = defaultRoute || path || '/';
  for (let key in routeItems) {
    let route = {
      path: path + '/' + key.toLocaleLowerCase().replace(/_/ig, '/'),
      name: key.replace(/_/ig, ''),
      meta: {},
      component: routeItems[key]
    };
    route.children = setRoutes(routeItems[key].children, route.path, '', callback);
    // 默认路由
    first && (route.alias = defaultRoute);
    first = false;
    typeof callback === 'function' && callback(route);
    res.push(route);
  }
  res.push({ path: '**', redirect: defaultRoute });
  return res;
};


let routes = setRoutes(pages, '', '', item => {
  // 是否需要登录
  // item.meta.auth = true;

  // 处理特殊组件
  switch (item.path) {
    case '/invitation':
      item.meta.title = '邀请有奖';
      break;
    case '/scholarship':
      item.meta.title = '我的奖学金';
      break;
    case '/indexpage':
      break;
    case '/cashout':
      item.meta.title = '提现';
      break;
    case '/dicresults':
      item.path = '/dicresults/:type';
      item.meta.title = '词典';
      break;
    case '/classlist':
      item.path = '/classlist/:type/:xid?';
      item.meta.title = '课程列表';
      break;
    case '/courselist':
      item.path = '/courselist/:type';
      break;
    case '/classdetail':
      item.path = '/classdetail/:cid';
      break;
    case '/audiodetail':
      item.path = '/audiodetail/:cid';
      item.meta.title = '有声专区';
      break;
    case '/playvideo':
      item.path = '/playvideo/:cid/:vid';
      break;
    case '/paysuccess':
      item.meta.title = '支付结果';
      item.meta.noHeaderDownload = true;
      item.meta.noGoHome = true;
      break;
    case '/payvip':
      item.meta.title = '购买会员';
      item.meta.noHeaderDownload = true;
      item.meta.noGoHome = true;
      item.path = '/payvip/:id';
      break;
    case '/paycount':
      item.meta.noHeaderDownload = true;
      item.meta.noGoHome = true;
      item.meta.title = '小学名师课堂直播课购买数据统计';
      break;
    case '/payviplist':
      item.meta.noHeaderDownload = true;
      item.meta.noGoHome = true;
      item.meta.title = '购买会员';
      break;
    case '/cashoutrecord':
      item.meta.title = '提现记录';
      break;
    case '/mycollect':
      item.meta.title = '我的收藏';
      break;
    case '/myorder':
      item.meta.title = '我的订单';
      break;
    case '/exchange':
      item.meta.title = '有奖兑换';
      break;
    case '/bind':
      item.meta.title = '绑定手机';
      break;
    case '/playaudio':
      item.path = '/playaudio/:cId/:rId/:rName';
      item.meta.noHeaderDownload = true;
      break;
    case '/tbcourselist':
      item.meta.title = '同步课程';
      break;
    case '/playrecord':
      item.meta.title = '播放记录';
      break;
  }
});

const router = new Router({
  // mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 };
  }
});

let ua = navigator.userAgent.toLowerCase();
let regNavigator = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;


// /* 使用假的微信用户信息
function testWxInfo(uid = '', params = {}) {
  let user = {
    uid,
    is_register: !!uid
  };
  let res = {
    'openid': 'oZrAp1NKowGyEuleaY7Hrsb-nVHc',
    'nickname': '我去好',
    'sex': 2,
    'language': 'zh_CN',
    'city': '\u5e7f\u5dde',
    'province': '\u5e7f\u4e1c',
    'country': '\u4e2d\u56fd',
    'headimgurl': 'http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/fadR31jcb7GYVibWzEcNIYsktgXFu5ZlGgzVgoOQXFnE5icUdWdwR0ibNB5ycSjSInccPfzG7iazA5pKOngicZ6Snfw\/132',
    'privilege': [],
    'unionid': 'oMQY9xCSh6MJBFkr3eVD4WQKMZgw'
  };
  params.nickname = res.nickname;
  res.nickname = '\\u' + res.nickname.split('').map(s => ('0000' + s.charCodeAt().toString(16)).slice(-4)).join('\\u');
  params.realname = res.nickname;
  params.unionid = res.unionid;
  params.openid = res.openid;
  params.icon = res.headimgurl;
  params.content = res;
  store.commit('setWxUserInfo', Object.assign(params, user));
  if (user.uid) {
    store.commit('setUserInfo', { uid: user.uid });
  }
}

/*  */


// 初始化产品
function initProductInfo($route, next) {
  let productInfoObj = store.getters.productInfo;
  if (!isChannel) {
    // 非渠道版
    store.commit('setProductInfo', {
      product_id: isXxtb ? 1 : 9,
      channel_id: isXxtb ? 23 : zxxfdb_id,
      terminal_id: 5
    });
  } else {
    let { channel_id: channel, key } = $route.query;
    channel = +channel;
    if (channel === 73) {
      key = Base64.encode(`37&73&西子K12空中课堂`);
    } else if (channel) {
      // 23 为分销版
      key = Base64.encode(isXxtb ? `1&${channel}&同步小学课堂` : `9&${channel}&中小学辅导班`);
    }
    if (key) {
      key = decodeURIComponent(key);
      let [product_id, channel_id, title] = Base64.decode(key)
        .split('&')
        .map(e => +e || e);
      channel_id = +channel_id || '';
      if (store.state.disChannel.includes(channel_id)) return next('/notchannel');
      if (
        product_id !== productInfoObj.product_id
        || channel_id !== productInfoObj.channel_id
        || title !== productInfoObj.title
      ) {
        store.commit('setUserInfo', {});
        store.commit('setWxUserInfo', {});
        store.commit('setIsLogin', false);
        Object.assign(productInfoObj, { product_id, channel_id, title });
        store.commit('setProductInfo', productInfoObj);
        store.commit('setAllCourse', {});
      }
    }
  }
  // store.commit('setHasAudio', !isXxtb && (+productInfoObj.channel_id === +zxxfdb_id));
  store.commit('setHasAudio', !isXxtb || +productInfoObj.channel_id === 23);
  store.commit('setIsWx', isXxtb && !isChannel);
}

router.beforeEach((to, from, next) => {
  buildType !== 'production' && testWxInfo();
  let defaultTitle = isXxtb ? '同步小学课堂' : '中小学辅导班';
  initProductInfo(to, next);
  document.title = to.meta.title || store.state.productInfo.title || defaultTitle;
  if (store.getters.isWx) {
    // 设置底部tab
    let ind = ['IndexPage', 'TbCourseList', 'Mine'].indexOf(to.name);
    if (ind === -1) {
      ind = 0;
    }
    store.commit('setActiveTab', ind + 1);
  }
  next();
});

export default router;
